package com.lm.service.impl;

import com.lm.dao.CheckCodeDao;
import com.lm.model.CheckCode;
import com.lm.service.CheckCodeService;
import com.lm.utils.ConfigUtil;
import com.meirengu.common.StatusCode;
import com.meirengu.model.Result;
import com.meirengu.service.impl.BaseServiceImpl;
import com.meirengu.utils.HttpUtil;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * CheckCode服务实现层
 *
 * @author Mao
 * @create Sat May 05 16:30:36 CST 2018
 */
@Service
public class CheckCodeServiceImpl extends BaseServiceImpl<CheckCode> implements CheckCodeService {
    private static final Logger logger = LoggerFactory.getLogger(CheckCodeServiceImpl.class);

    @Autowired
    CheckCodeDao checkCodeDao;

    @Override
    public int generate() {
        return RandomUtils.nextInt(100000, 999999);
    }

    @Override
    public HttpUtil.HttpResult send(String mobile, int code, String ip, String type) {
        HttpUtil.HttpResult hr = null;
        Map<String, String> params = new HashMap<String, String>();
//        params.put("tpl_id", type);
        params.put("mobile", mobile);
        params.put("ip", ip);
//        params.put("code", code+"");
        String text = "【大额推广】您的验证码是：" + code;

        params.put("text", text);
        String url = ConfigUtil.getConfig("URI_CHECKCODE_SEND");
        logger.info("CheckCodeServiceImpl.send post >> uri :{}, params:{}", new Object[]{url, params});
        try {
            hr = HttpUtil.doPostForm(url, params);
        } catch (Exception e) {
            logger.error("CheckCodeServiceImpl.send error >> params:{}, exception:{}", new Object[]{params, e});
        }
        return hr;
    }

    @Override
    public int create(CheckCode checkCode) {
        return checkCodeDao.create(checkCode);
    }

    @Override
    public int update(CheckCode checkCode) {
        return checkCodeDao.update(checkCode);
    }

    @Override
    public CheckCode retrieve(String mobile, int code) {
        Map params = new HashMap();
        params.put("mobile", mobile);
        params.put("code", code);
        return checkCodeDao.retrieve(params);
    }

    public String SMS(String postData, String postUrl) {
        try {
            //发送POST请求
            URL url = new URL(postUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setUseCaches(false);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Length", "" + postData.length());
            //设置连接主机超时
            conn.setConnectTimeout(5000);
            //设置从主机读取数据超时
            conn.setReadTimeout(5000);
            OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(postData);
            out.flush();
            out.close();
            //获取响应状态
            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                System.out.println("connect failed!");
                return "";
            }
            //获取响应内容体
            String line, result = "";
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while ((line = in.readLine()) != null) {
                result += line + "\n";
            }
            in.close();
            return result;
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
        return "";
    }

    public Result singleSend(String mobile, int code, String ip, String type) throws Exception {
        Result result = new Result();
        String text = "【卡王贷】您的验证码是：" + code;
        logger.info("SmsServiceImpl.singleSend params >> mobile:{}, text:{}", new Object[]{mobile, text});
        String domain = ConfigUtil.getConfig("SMS_DOMAIN");
        String uid = ConfigUtil.getConfig("SMS_UID");
        String pw = ConfigUtil.getConfig("SMS_PW");
        String PostData = "uid=" + uid + "&pw=" + pw + "&mb=" + mobile + "&ms=" + java.net.URLEncoder.encode(text, "utf-8");
        String ret = SMS(PostData, "http://" + domain + "/send.do");

        if (StringUtils.isNotBlank(ret)) {
            if (ret.contains(",")) {
                String[] retarr = ret.split(",");
                code = Integer.parseInt(retarr[0]);
                logger.info(retarr[1]);
                if (code == 0) {
                    result.setCode(StatusCode.OK);
                    result.setMsg(StatusCode.codeMsgMap.get(StatusCode.OK));
                }
            }

        }
        return result;
    }
}
